######################################################################
# Time-stamp: <05/08/09 17:02:20 ostolop>
######################################################################
package EP::EPC::Core::Sequence_Management;

use strict;

use EP::Config;
use EP::Common;
use EP::Common::General;
use EP::Common::Error qw ( :try );

use EP::EPC::Core;
use EP::EPC::Core::Component;

use EP::Core::Data::Parser::seq;
use EP::Core::Dataset::Data::seq;

use File::Temp;
use Bio::DB::GFF;

use base qw ( EP::EPC::Core::Component );

sub process_component {
  my $self = shift;

  my $new_dataset = $self->process_sequence_management();
  my $process_result = {
			src_dataset_id => $self->{src_dataset}->id,
			dst_dataset_id => $new_dataset->id
		       };

  $self->{CD}->{process_result} = $process_result;
  $self->record_analysis_history ();
  return OK;
}

sub process_sequence_management {
  my $self = shift;

  my @ids;
  if ( $self->{query}->param ( 'dataset_only' ) !~ 'not_ds' ) {

    if ( $self->{src_dataset}->type eq 'exp' ) {
	@ids = map{ $self->{src_dataset}->data->rows->{$_}{full_annot}{NAMES} } sort { $a <=> $b } keys %{ $self->{src_dataset}->data->rows };
    }

    if ( $self->{src_dataset}->type eq 'seq' ) {
      while ( my $seq = $self->{src_dataset}->data->{sequences}->next_seq() ) {
	push @ids, $seq->id;
      }
    }
  }

  if ( $self->{query}->param ( 'dataset_only' ) !~ 'ds' ) {
    push @ids, split /\r\n|\r|\n/, $self->{query}->param('genes');
  }

  if ( scalar @ids == 0 ) {
    die "No gene IDs found!";
  }

  $self->{session}->status( "Retrieving sequences ..." );
  my $dataset = $self->{src_dataset}->copy( { name => undef } );
  $dataset->type( 'seq' );
  my $seq = EP::Core::Data::Parser::seq->_get_sequences ( $self->{src_dataset}->species, \@ids );  
  my $data = new EP::Core::Dataset::Data::seq( sequences => $seq );
  $data->start_bp( -1 * $self->{query}->param('upstream_bp') );
  $data->end_bp( -1 );
  $dataset->data ( $data );

  $self->{session}->status( "Saving dataset ..." );
  EP::Core::Data::Parser::seq->_write_dataset_data ( $dataset );
  $dataset->data->process_metadata();

  return $dataset;
}

1;
